<?php

namespace Wonfu\Core;

use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;

class Utils
{
    /**
     * 生成唯一请求号
     * @return string
     */
    public static function genrateUniReqNo()
    {
        return sprintf('%s-%s', getmypid(), uniqid());
    }


    /**
     * 字符串变成小驼峰
     * @param string $str 待处理字符串
     * @return string        结果字符串
     */
    static public function toLittleHump($str)
    {
        $arr = preg_split('/_|-/', $str);
        if (count($arr) == 1) {
            return $str;
        }
        $isFirst = true;
        foreach ($arr as &$value) {
            $value = strtolower($value);
            if ($isFirst) {
                $isFirst = false;
                $value = lcfirst($value);
            } else {
                $value = ucfirst($value);
            }
        }
        return implode('', $arr);
    }

    /**
     * 字符串变成大驼峰
     * @param type $str 待处理字符串
     * @return string        结果字符串
     */
    static public function toBigHump($str)
    {
        $arr = preg_split('/_|-/', $str);
        foreach ($arr as &$value) {
            $value = ucfirst($value);
        }
        return implode('', $arr);
    }

    /**
     * 将驼峰字符串变成C风格(下划线)
     *
     * @param string $str
     * @return string
     */
    public static function toCStyle($str)
    {
        return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $str), "_"));
    }

    /**
     * @param $data
     * @param $mapper
     * @return mixed
     */
    public static function ObjectMapper($data, $mapper)
    {
        $encoders = [new XmlEncoder(), new JsonEncoder()];
        $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
        $normalizers = [new ObjectNormalizer(null, null, null, $extractor),
            new ArrayDenormalizer(), new JsonSerializableNormalizer()];
        $serializer = new Serializer($normalizers, $encoders);
        return $serializer->deserialize($data, $mapper, 'json', [
            ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true]);
    }


}